package com;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/ws",port= "9001",workerLoopGroupThreads = "2")
public class WebSocketServer {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisUtil redisUtil;

    public static ConcurrentHashMap<String, Session> channelGroup = new ConcurrentHashMap<>();

    public static  final  String SERVER_NAME = "ws2";

    private Integer count = 0;

    @OnMessage
    public void onMessage(Session session, String message) {
        JSONObject jsonObject = JSONUtil.parseObj(message);
        ChatMessage chatMessage = new ChatMessage();
        // 强转为消息类型
        jsonObject.forEach((key, value) -> BeanUtil.setProperty(chatMessage, StrUtil.toCamelCase(key), value));
        if (chatMessage.getType() == 0) {
            JSONObject json = redisUtil.get(String.valueOf(chatMessage.getSaver()), JSONObject.class);
            if(json == null){
                chatMessage.setContent("用户不在线");
                session.sendText(JSONUtil.toJsonStr(chatMessage));
            }else {
                System.out.println(json.get("channel",String.class));
                chatMessage.setSerChId(json.get("channel",String.class));
                rabbitTemplate.convertAndSend(Confgtations.EX_WEBSOCKET, json.get("server",String.class),chatMessage);
            }
        }
    }

    @BeforeHandshake
    public void handshake(Session session, HttpHeaders headers, @RequestParam String token,@RequestParam String id,@RequestParam String name ){
        if (!"ok".equals(token)){
            session.sendText("Authentication failed!");
            session.close();
        }
    }

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, @RequestParam String token,@RequestParam String id,@RequestParam String name ){
        session.channel().attr(AttributeKey.valueOf("userId")).set(id);
        redisUtil.set(id,JSONUtil.createObj().
                putOnce("server",SERVER_NAME)
                .putOnce("name",name)
                .putOnce("channel",session.channel().id().toString())
        );
        channelGroup.put(session.channel().id().toString(),session);

        System.out.println("连接数" + channelGroup.size());
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        String s = session.channel().attr(AttributeKey.valueOf("userId")).get().toString();
        redisUtil.del(s);
        channelGroup.remove(session.channel().id().toString());
        System.out.println("断开连接，当前在线：" + channelGroup.size());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
        session.close();
    }



    @OnBinary
    public void onBinary(Session session, byte[] bytes) {
        for (byte b : bytes) {
            System.out.println(b);
        }
        session.sendBinary(bytes);
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    System.out.println(session.channel().id().toString()+" read idle");
                    break;
                case WRITER_IDLE:
                    System.out.println(session.channel().id().toString()+" write idle");
                    break;
                case ALL_IDLE:
                    System.out.println(session.channel().id().toString()+" all idle");
                    break;
                default:
                    break;
            }
        }
    }

}
